import React, {useState,useContext,useEffect} from "react";
import { AppContext } from "../../reHook/start";
import { base, createPage } from 'nc-lightapp-front';
import HrTree from 'src/hrpub/common/components/hrTree/index'
import {Content,Form} from "./components/style"
import { SInput,SSelect,SCheckbox } from "./components/scontrols/index.js";

import Util from '../../model/util.js'
import "./index.less";
const { NCTable,NCTabs,NCTabsControl,NCInput, NCButton } = base;
const NCTabPane = NCTabs.NCTabPane;

const columns = [
    { title: '信息项', dataIndex: 'name', key: 'psn_doc', width: 100 },
];
const columns2 = [
    { title: '系统变量', dataIndex: 'm_field_name', key: 'systemData', width: 100 },
];  
const columns3 = [
    { title: '筛选变量', dataIndex: 'fieldcode', key: 'filterData', width: 200 },
    { title: '筛选条件', dataIndex: 'sqldscrpt', key: 'filterSqlScript', width: 100 },
]; 
// const data2 = {
//     m_data_type: ["15", "8", "1"],
//     m_field_code: ["CURR_DATE", "CURR_TIME", "CURR_USER"],
//     m_field_name: ["日期", "时间", "用户"],
// }

function Pannel(props){
    const {ab,dispatch} = useContext(AppContext)
    let currentDocId = wps.PluginStorage.getItem('currentDocId')
    console.log('wwwww')
    useEffect(()=>{
        // let key = wps.PluginStorage.getItem("pk_rpt_def")
        let isPluginStorage = wps.PluginStorage.getItem('PluginStorage')
        console.log('跨页面获取所有数据！', isPluginStorage, currentDocId)
        if(currentDocId){
            if(isPluginStorage) {
                console.log("从PluginStorage中获取对应的数据！！！！")
                let allData = Util.deepCopy(JSON.parse(wps.PluginStorage.getItem(currentDocId)));
                console.log('allData', allData)
                updateAll(allData)
            } else{
                let request = window.indexedDB.open('wps',1);
                let db;
                request.onerror = function (e) {
                    console.log("wps数据库打开失败");
                   
                }
                request.onsuccess = function(e){
                    console.log('打开数据库成功！')
                    db = request.result;
                    var transaction = db.transaction(['taskpane']);
                    var objectStore = transaction.objectStore('taskpane');
                    var objStore = objectStore.get(currentDocId);
        
                    objStore.onerror = function(event) {
                        console.log('事务失败');
                    };
        
                    objStore.onsuccess = function(event) {
                        if (objStore.result) {
                            console.log("从数据库中获取对应的数据！！！！",objStore.result.allData)
                            let allData = Util.deepCopy(objStore.result.allData);
                            updateAll(allData)
                        } else {
                            console.log('未获得数据记录');
                        }
                    };
                }
            }
        }
    },[currentDocId])
    useEffect(()=>{
        let AllTable = Util.deepCopy(ab.tableMap)
        if(ab.chooseKey && ab.chooseKey !== ''){
            if(ab.flag === 1){
                for(let key in AllTable){
                    if(key === ab.selectKeys[0]){
                        AllTable[key].map(item=>{
                            if(item.key === ab.chooseKey || item.m_field_code == ab.chooseKey){
                                item.style = {backgroundColor:'#ffebee'}
                            }
                        })
                    }
                }
            }else if(ab.flag === 2){
                let currentTable = Util.deepCopy(ab.systemTableData)
                currentTable.map(item=>{
                    if(item.m_field_code == ab.chooseKey){
                        item.style = {backgroundColor:'#ffebee'}
                    }else{
                        item.style = {}
                    }
                })
                dispatch({
                    type:'ab/update',
                    payload:{
                        systemTableData:currentTable
                    }
                })
            }else if(ab.flag === 3){
                let currentTable = Util.deepCopy(ab.highConfig)
                currentTable.map(item=>{
                    if(item.id === ab.chooseKey){
                        item.style = {backgroundColor:'#ffebee'}
                    }else{
                        item.style = {}
                    }
                })
                dispatch({
                    type:'ab/update',
                    payload:{
                        highConfig:currentTable
                    }
                })
            }
            dispatch({
                type:'ab/update',
                payload:{
                    selectTable:AllTable[ab.selectKeys[0]]
                }
            })
        }
    },[ab.chooseKey])
    const updateAll = (allData)=>{
        if(allData){
            let hashMap = Util.deepCopy(allData.InfoSet);
            let tableMap = {}
            let treeData = hashMap.map((item,index)=>{
                if(item.children && item.children.length > 0){
                    if(!tableMap[item.key]){
                        tableMap[item.key] = item.children
                    }else{
                        console.log("??? ma sa ka???")
                    }
                    item.children = [];
                    return item
                }
            })
            let sysTemData = Util.deepCopy(allData.SysVars);
            let highConfigData = Util.deepCopy(allData.condition)
            let firstKey = treeData[0].key
            let selectKeys = [];
            selectKeys.push(firstKey)
            dispatch({
                type:'ab/update',
                payload:{
                    allValue:{
                        code: allData.RptCode, //编码
                        name: allData.RptName, //表名
                        checkselect:'最近第', // 信息项定位的默认
                        checkdetail:1,// 具体的控制
                        date:'0',//日期格式
                    },
                    selectTable:tableMap[selectKeys[0]],
                    option:allData.DateFormat,
                    allTree:allData.InfoSet,
                    selectKeys:selectKeys,
                    checkoption:allData.SelectName, //序号选择
                    treeData:treeData, //信息集树的数据
                    tableMap:tableMap, //信息集表格的映射数据
                    systemTableData:sysTemData, //系统变量
                    highConfig:highConfigData //高级系统参数设置
                }
            })
        }
    }
    // 若为信息项或系统变量的话，需要自拼接链接和字段
    const appendPageHref=(name,target, dateDisableControl,checkdisabled)=>{
        let before = ''
        let add = ''
        let addCode = ''
        if(ab.allValue.before && ab.allValue.before !== ''){
            before = `'${ab.allValue.before}'+`
        }
        // !ab.checkdisabled
        if(!checkdisabled && ab.allValue.checked && ab.allValue.checked == 'numcheck'){
            let checkSelectRealValue = ''
            let targetArr = target.split('.');
            switch (ab.allValue.checkselect) {
                case '最近第':
                    checkSelectRealValue = ''
                    targetArr[0] = targetArr[0]+ 'new' + ab.allValue.checkdetail;
                    break;
                case '最近': // + new
                    checkSelectRealValue = '0:'
                    // hi_psndoc_abroad.abroadgroup
                    targetArr[0] = targetArr[0]+ 'new' + ab.allValue.checkdetail;
                    break;
                case '最初第':
                    checkSelectRealValue = '-'
                    targetArr[0] = targetArr[0]+ 'old' + ab.allValue.checkdetail;
                    break;
                case '最初': // + old
                    checkSelectRealValue = '0:-'
                    targetArr[0] = targetArr[0]+ 'old' + ab.allValue.checkdetail;
                    break;
                default:
                    break;
                }
            target = targetArr.join('.')
            add += '['+ab.allValue.checkselect+ab.allValue.checkdetail+'条]'
            addCode += `[${checkSelectRealValue}${ab.allValue.checkdetail}]`
        }
        // !ab.DateDisableControl
        if(!dateDisableControl){
            let index = parseInt(ab.allValue.date)
            add += `(${ab.option[index].display}+${ab.allValue.date})`
            addCode += `(${ab.option[index].display}+${ab.allValue.date})`
        }
        if(ab.allValue.after && ab.allValue.after !== ''){
            add += `+'${ab.allValue.after}'`
            addCode += `+'${ab.allValue.after}'`
        }
        // !ab.checkdisabled
        if(!checkdisabled && ab.allValue.childline && ab.allValue.childline !== ''){
            add += `-'${ab.allValue.childline}'`
            addCode += `-'${ab.allValue.childline}'`
        }
        let displayName = '@'+before+name+add+'@';
        let displayCode = '{'+before+target+addCode+'}'

        WpsHyperlinksAdd(displayName,displayCode)
    }

    //wps最终填充结构显示
    const WpsHyperlinksAdd=(displayName,displayCode)=>{
        let l_Doc = wps.WpsApplication().ActiveDocument;
        let Selection = wps.WpsApplication().Selection
        let area = l_Doc.Range(Selection.Start,Selection.Start);
        console.log("--------------------------函数结束，开始添加！---------------------------------")
        area.InsertBefore(displayName)
        area.Font.Name = "SimSun"
        area.Font.Size = 10.5
        l_Doc.Hyperlinks.Add(area,displayCode)
        area.Font.Underline =Util.WPS_Enum.wdUnderlineNone
        area.Font.ColorIndex = Util.WPS_Enum.wdAuto //wdGreen
        // ScreenTip 鼠标指针停留在超链接上时所显示的屏幕提示
        // 第一个元素的屏幕显示
        // l_Doc.Hyperlinks.Item(1).ScreenTip = displayCode
    }
    //所有table双击事件控制
    const doubleClick = async (record, index, event)=>{
        let name,target
        // if((record.m_field_code && record.m_field_code !== ab.chooseKey) || (record.key && record.key!==ab.chooseKey)){ 
        let allState = updateCurrentState(record)
        await dispatch({
            type:'ab/update',
            payload:{
                chooseKey:allState.chooseKey,
                checkdisabled:allState.checkdisabled,
                DateDisableControl:allState.DateDisableControl
            }
        })
        // }
        if(record.href_path){
            WpsHyperlinksAdd(record.href_name,record.href_path)
        }else{
            if(record.m_field_name && record.m_data_type){
                name = record.m_field_name;
                target = record.m_field_code
            }else{
                name = record.name;
                target = record.code
            }
            console.log(name,target)
            // 不能及时更新  传过去
            appendPageHref(name,target, allState.DateDisableControl, allState.checkdisabled)
        }
        
        
    }
    const singleClick = (record, index, event)=>{
        let allState = updateCurrentState(record)
        dispatch({
            type:'ab/update',
            payload:{
                chooseKey:allState.chooseKey,
                checkdisabled:allState.checkdisabled,
                DateDisableControl:allState.DateDisableControl
            }
        })
            
    }
    const updateCurrentState=(record)=>{
        let checkdisabled = false;
        let DateDisableControl = false
        let chooseKey = ""
        if(record.href_path){
            chooseKey = record.id
            checkdisabled=true
            DateDisableControl=true
        }else{
            if(record.m_field_name && record.m_data_type){
                chooseKey = record.m_field_code
                checkdisabled=false
               if(record.m_data_type === "20" || record.m_data_type === "15"){
                DateDisableControl=false
               }else{
                DateDisableControl=true
               }
            }else{
                chooseKey = record.key
                DateDisableControl=!record.nodeData.nodeValue.hashValue.datecontrol
                checkdisabled=!record.nodeData.nodeValue.hashValue.linecontrol
            }
        }
        return {
            chooseKey,
            checkdisabled,
            DateDisableControl
        }
    }
    const valueChange = (type)=>{
        return (value) =>{
            console.log(type+'类型的值为'+value)
            let newValue = Util.deepCopy(ab.allValue)
            newValue[type] = value
            dispatch({
                type:'ab/update',
                payload:{
                    allValue: newValue
                }
            })
        }
    } 
    
    const checkForm = (flag) => {
        console.log(flag);
        dispatch({
            type:'ab/update',
            payload:{
                flag: flag
            }
        })
        if(ab.flag === 1){
            let AllTable = Util.deepCopy(ab.tableMap)
            dispatch({
                type:'ab/update',
                payload:{
                    selectTable:AllTable[ab.selectKeys[0]]
                }
            })

        }
        if(ab.flag === 3 || ab.flag === 2){
            let AllTable = ab.flag === 3?Util.deepCopy(ab.highConfig):Util.deepCopy(ab.systemTableData)
            let currentKey = ab.flag === 3?'highConfig':'systemTableData'
            AllTable.map(item=>{
                if(item.style && item.style.backgroundColor){
                    item.style = {}
                }
            })
            dispatch({
                type:'ab/update',
                payload:{
                    [currentKey]:AllTable
                }
            })
        }
    }
    const selectTree = (key)=>{
        let selectKey = key
        dispatch({
            type:'ab/update',
            payload:{
                selectKeys:selectKey,
                selectTable:ab.tableMap[selectKey[0]],
            }
        })
        console.log(key)
    }
    const checkoutChange = (value,type)=>{
        console.log(value)
    }

    const getItemSetting = async() => {
        // console.log(ab)
        let key = localStorage.getItem("pk_rpt_def")
        console.log('跨页面获取所有数据！',key)
        if(key){
            let request = window.indexedDB.open('wps',1);
            let db;
            request.onerror = function (e) {
                console.log("wps数据库打开失败");
            }
            request.onsuccess = function(e){
                console.log('打开数据库成功！')
                console.log('打开数据库成功！')
                db = request.result;
                var transaction = db.transaction(['taskpane']);
                var objectStore = transaction.objectStore('taskpane');
                var objStore = objectStore.get(key);
    
                objStore.onerror = function(event) {
                    console.log('事务失败');
                };
    
                objStore.onsuccess = function(event) {
                    if (objStore.result) {
                        console.log("从数据库中获取对应的数据！！！！",objStore.result.allData)
                        let allData = Util.deepCopy(objStore.result.allData);
                        let postData = {
                            "key":allData.key,'appcode':allData.appcode,
                            conditionDesignFlag: true,
                            pk_infoset: '1002Z7100000000046GP',  //ab.chooseKey// '1002Z7100000000046GP',
                            "internalDataFactory": "nccloud.web.hrhi.rptdef.factory.RtfDownloadFactory"
                        }
    
                        Util._Ajax("/nccloud/hr/login/InternalAction.do",postData).then(res => {
                            console.log('wwwwwwwwwwwwww')
                            console.log(res)
                        });

                    } else {
                        console.log('未获得数据记录');
                    }
                };
            }
           
        }
       
    //     var GetUrlPath = ()=> {
    //         var e = document.location.toString();
    //         return -1 != (e = decodeURI(e)).indexOf("/") && (e = e.substring(0, e.lastIndexOf("/"))), e
    //     }
    //     var url = GetUrlPath();
    //     console.log('url........',url)
       
    Util.OnShowDialog("taskpane2", "子集取数条件", 900, 500, true, false)
    // let tskpane = wps.GetTaskPane(testid)
    // tskpane.Visible = !tskpane.Visible
    }

    
    
    return (
        <div className = "main">
            <Content name = {'基本信息'} gray = {true}>
                <SInput name={'编码'}
                    value = {ab.allValue.code}
                    onChange = {valueChange('code')}
                />
                <SInput name={'名称'}
                    value = {ab.allValue.name}
                    onChange = {valueChange('name')}
                />
            </Content>
            <Content name = {'字段选择'}>
                <div className="tree-area">
                    <NCTabsControl defaultKey={0}>
                        <div key={1} clickFun={()=>checkForm(1)}>{'信息集'}</div>
                        <div key={2} clickFun={()=>checkForm(2)}>{'系统变量'}</div>
                        <div key={3} clickFun={()=>checkForm(3)}>{'条件筛选'}</div>
                    </NCTabsControl>
                    <If condition = {ab.flag == 1}>
                        <div className = "container">
                            <div className = "leftTree">
                            <HrTree
                                treeData = {ab.treeData}
                                config = {{
                                            checkable:false,
                                            showRoot:true,
                                            root:{
                                                title: '信息集',
                                                key: '0-0',
                                                // innercode:'N'
                                            },
                                            checkStrictly:false,
                                            onSelect:selectTree,
                                            selectedKeys:ab.selectKeys,
                                        }}
                                disableCheckbox = {false}
                                replaceChecked = {false}
                                // onCheck = {checkTree}
                                // checkedKeys = {job.CheckedKey}
                            />
                            </div>
                            <div className = "rightTable">
                                <NCTable
                                    columns={columns}
                                    onRowClick={singleClick}
                                    data={ab.selectTable}
                                    onRowDoubleClick = {doubleClick}
                                />
                            </div>
                        </div>
                    </If>
                    <If condition = {ab.flag == 2}>
                        <NCTable
                            columns={columns2}
                            onRowClick={singleClick}
                            data={ab.systemTableData}
                            onRowDoubleClick = {doubleClick}
                        />
                    </If>
                    <If condition = {ab.flag == 3}>
                        <NCTable
                            columns={columns3}
                            onRowClick={singleClick}
                            data={ab.highConfig}
                            onRowDoubleClick = {doubleClick}
                        />
                    </If>
            </div>
            </Content>
            <Content name = {'高级设置'} padding = {true}>
                {/* <NCButton onClick={getItemSetting}>{'子集取数条件'}</NCButton> */}
                <Form name = {'信息项定位'}>
                    <SCheckbox 
                        // width = {'260px'}
                        selectedValue = {ab.allValue.checked}
                        disabled={ab.checkdisabled}
                        onChange = {valueChange('checked')}
                        value = {ab.allValue.checkselect}
                        option = {ab.checkoption}
                        selectChange = {valueChange('checkselect')}
                        checkDetail = {ab.allValue.checkdetail}
                        ControlChange = {valueChange('checkdetail')}
                    />
                    
                </Form>
                <Form name = {'子集显示行数'}>
                    <SInput name={'子集显示行数'}
                        width = {'260px'}
                        disabled={ab.checkdisabled}
                        value = {ab.allValue.childline}
                        onChange = {valueChange('childline')}
                    />
                </Form>
                <Form name = {'日期'}>
                    <SSelect name={'日期格式'}
                        value = {ab.allValue.date}
                        disabled={ab.DateDisableControl}
                        option = {ab.option}
                        onChange = {valueChange('date')}
                    />
                </Form>
                <Form name = {'扩充文本'}>
                    <SInput name={'前缀'}
                        width = {'260px'}
                        value = {ab.allValue.before}
                        onChange = {valueChange('before')}
                    />
                    <SInput name={'后缀'}
                        width = {'260px'}
                        value = {ab.allValue.after}
                        onChange = {valueChange('after')}
                    />
                </Form>
            </Content> 
            {/* <div style={{
                    display: 'none',
                }}>
                    {props.search.NCCreateSearch('ConditionQuery', {
                        searchBtnName: '确定',
                        onlyShowAdvArea: false,
                        showAdvSearchPlanBtn: true,
                        saveSearchPlan: true,
                        onlyShowSuperBtn: true,
                        // clickSearchBtn: () => {this.goSearch()}
                    })}
                </div>                     */}
                {/* <QueryConfirm></QueryConfirm> */}
                
        </div>
    )
    
}

export default createPage({})(Pannel)